import sys
import random
from PySide6.QtWidgets import (QApplication, QMainWindow, QTableWidget, QTableWidgetItem,
                               QWidget, QVBoxLayout, QHBoxLayout, QPushButton, QLabel,
                               QSpinBox, QMessageBox)
from PySide6.QtCore import Qt
from PySide6.QtGui import QFont


class PaginatedTable(QMainWindow):
    def __init__(self):
        super().__init__()

        # 设置窗口基本属性
        self.setWindowTitle("带分页功能的表格")
        self.setGeometry(100, 100, 800, 600)

        # 数据相关属性
        self.total_data = []  # 所有数据
        self.current_page = 1  # 当前页码
        self.items_per_page = 10  # 每页显示的行数

        # 创建中心部件和布局
        self.central_widget = QWidget()
        self.setCentralWidget(self.central_widget)
        self.main_layout = QVBoxLayout(self.central_widget)

        # 创建表格
        self.create_table()

        # 创建分页控件
        self.create_pagination_controls()

        # 生成示例数据
        self.generate_sample_data(157)  # 生成157条示例数据，方便测试分页

        # 显示第一页数据
        self.update_table()

    def create_table(self):
        """创建表格组件"""
        self.table = QTableWidget()
        self.table.setColumnCount(4)  # 4列数据
        self.table.setHorizontalHeaderLabels(["ID", "名称", "数值", "状态"])

        # 设置表格样式
        self.table.horizontalHeader().setStretchLastSection(True)
        self.table.setAlternatingRowColors(True)
        self.table.setFont(QFont("SimHei", 10))

        self.main_layout.addWidget(self.table)

    def create_pagination_controls(self):
        """创建分页控制组件"""
        pagination_widget = QWidget()
        pagination_layout = QHBoxLayout(pagination_widget)

        # 首页按钮
        self.first_btn = QPushButton("首页")
        self.first_btn.clicked.connect(self.go_to_first_page)

        # 上一页按钮
        self.prev_btn = QPushButton("上一页")
        self.prev_btn.clicked.connect(self.go_to_prev_page)

        # 页码显示
        self.page_label = QLabel()

        # 下一页按钮
        self.next_btn = QPushButton("下一页")
        self.next_btn.clicked.connect(self.go_to_next_page)

        # 末页按钮
        self.last_btn = QPushButton("末页")
        self.last_btn.clicked.connect(self.go_to_last_page)

        # 每页行数选择
        self.items_per_page_label = QLabel("每页行数:")
        self.items_per_page_spin = QSpinBox()
        self.items_per_page_spin.setMinimum(5)
        self.items_per_page_spin.setMaximum(50)
        self.items_per_page_spin.setValue(self.items_per_page)
        self.items_per_page_spin.valueChanged.connect(self.change_items_per_page)

        # 添加控件到布局
        pagination_layout.addWidget(self.first_btn)
        pagination_layout.addWidget(self.prev_btn)
        pagination_layout.addWidget(self.page_label)
        pagination_layout.addWidget(self.next_btn)
        pagination_layout.addWidget(self.last_btn)
        pagination_layout.addStretch()
        pagination_layout.addWidget(self.items_per_page_label)
        pagination_layout.addWidget(self.items_per_page_spin)

        self.main_layout.addWidget(pagination_widget)

    def generate_sample_data(self, count):
        """生成示例数据"""
        status_options = ["正常", "警告", "错误", "未知"]
        self.total_data = []

        for i in range(1, count + 1):
            name = f"项目{i:03d}"
            value = round(random.uniform(10, 1000), 2)
            status = random.choice(status_options)
            self.total_data.append((i, name, value, status))

    def get_total_pages(self):
        """计算总页数"""
        if not self.total_data:
            return 1
        return (len(self.total_data) + self.items_per_page - 1) // self.items_per_page

    def update_table(self):
        """更新表格数据"""
        total_pages = self.get_total_pages()

        # 确保当前页码有效
        if self.current_page < 1:
            self.current_page = 1
        elif self.current_page > total_pages:
            self.current_page = total_pages

        # 计算当前页显示的数据范围
        start_index = (self.current_page - 1) * self.items_per_page
        end_index = min(start_index + self.items_per_page, len(self.total_data))
        current_data = self.total_data[start_index:end_index]

        # 更新表格内容
        self.table.setRowCount(len(current_data))
        for row, (id_, name, value, status) in enumerate(current_data):
            self.table.setItem(row, 0, QTableWidgetItem(str(id_)))
            self.table.setItem(row, 1, QTableWidgetItem(name))
            self.table.setItem(row, 2, QTableWidgetItem(str(value)))

            # 设置状态单元格，并根据状态设置不同颜色
            status_item = QTableWidgetItem(status)
            if status == "正常":
                status_item.setBackground(Qt.green)
            elif status == "警告":
                status_item.setBackground(Qt.yellow)
            elif status == "错误":
                status_item.setBackground(Qt.red)
            else:
                status_item.setBackground(Qt.gray)

            self.table.setItem(row, 3, status_item)

        # 更新页码显示
        self.page_label.setText(f"第 {self.current_page} / {total_pages} 页")

        # 更新按钮状态
        self.first_btn.setEnabled(self.current_page > 1)
        self.prev_btn.setEnabled(self.current_page > 1)
        self.next_btn.setEnabled(self.current_page < total_pages)
        self.last_btn.setEnabled(self.current_page < total_pages)

    def go_to_first_page(self):
        """跳转到首页"""
        if self.current_page != 1:
            self.current_page = 1
            self.update_table()

    def go_to_prev_page(self):
        """跳转到上一页"""
        if self.current_page > 1:
            self.current_page -= 1
            self.update_table()

    def go_to_next_page(self):
        """跳转到下一页"""
        if self.current_page < self.get_total_pages():
            self.current_page += 1
            self.update_table()

    def go_to_last_page(self):
        """跳转到末页"""
        last_page = self.get_total_pages()
        if self.current_page != last_page:
            self.current_page = last_page
            self.update_table()

    def change_items_per_page(self, value):
        """改变每页显示的行数"""
        self.items_per_page = value
        self.current_page = 1  # 重置到第一页
        self.update_table()


if __name__ == "__main__":
    app = QApplication(sys.argv)

    # 确保中文显示正常
    font = QFont("SimHei")
    app.setFont(font)

    window = PaginatedTable()
    window.show()
    sys.exit(app.exec())
